<template>
  <div class="recommended-jobs">
    <div class="section-header">
<<<<<<< HEAD
      <h2>热门岗位推荐</h2>
=======
      <h2 @click="viewAll" class="clickable">热门岗位推荐</h2>
>>>>>>> resume
      <el-button type="text" @click="viewAll">查看全部 ></el-button>
    </div>
    
    <div class="jobs-grid">
      <job-card 
        v-for="job in jobs" 
        :key="job.id" 
        :job="job" 
        @click="viewJobDetail(job)"
<<<<<<< HEAD
=======
        @toggle-favorite="handleToggleFavorite"
>>>>>>> resume
      />
    </div>
  </div>
</template>

<script setup>
import JobCard from './JobCard.vue'
<<<<<<< HEAD
import { ref } from 'vue'

// 模拟热门岗位数据
const jobs = ref([
  {
    id: 1,
    title: '高级前端工程师',
    company: '腾讯科技',
    salary: '20K-35K',
    tags: ['全职', '远程'],
    location: '深圳',
    postedTime: '1天前',
    logo: 'https://ts1.tc.mm.bing.net/th/id/R-C.2b85a01aae17134a7bece8c14c19ebd0?rik=y6nFYeWYcGRL7w&riu=http%3a%2f%2fpro.statics.logoqs.techuangyi.com%2f2017%2f11%2f16%2feb88a7e8c855c159076bd72a19222082.png%3fx-oss-process%3dimage%2fresize%2cm_fill%2cw_312%2ch_175&ehk=y1%2fGcePuOF33KQg2gDWvFXaIaTrhKIMIbZRN6xae2d0%3d&risl=&pid=ImgRaw&r=0',
    background: 'https://ts1.tc.mm.bing.net/th/id/R-C.5c4b709dbfc5ee86a925e2b34ad6bf31?rik=MWQppvn7kT%2fWgg&riu=http%3a%2f%2fwww.szquanli.com%2fuploads%2fallimg%2f171123%2f2-1G123105G6.jpg&ehk=kkro5rWN1XYuq5UxxNolLOWgFprBZSX0FF7YWv%2bvqaM%3d&risl=&pid=ImgRaw&r=0' // 添加背景图片
  },
  {
    id: 2,
    title: 'Java架构师',
    company: '阿里巴巴',
    salary: '30K-50K',
    tags: ['全职'],
    location: '杭州',
    postedTime: '2天前',
    logo: 'https://tse3-mm.cn.bing.net/th/id/OIP-C.rJN_GeK5BREjkt818suvKAHaHa?o=7rm=3&rs=1&pid=ImgDetMain&o=7&rm=3',
    background: 'https://tse3-mm.cn.bing.net/th/id/OIP-C.maQ8gQQIfGvRJZKSGL7wSQHaEK?o=7rm=3&rs=1&pid=ImgDetMain&o=7&rm=3' // 添加背景图片
  },
  {
    id: 3,
    title: '产品经理',
    company: '字节跳动',
    salary: '25K-40K',
    tags: ['全职'],
    location: '北京',
    postedTime: '3天前',
    logo: 'https://logo800.cn/uploads/logoxinshang/56/logo800_16491624083325586.png',
    background: 'https://www.logo9.net/logoufpapers/images/536.jpg' // 添加背景图片
  },
  {
    id: 4,
    title: 'UI设计师',
    company: '美团',
    salary: '18K-30K',
    tags: ['全职', '弹性工作'],
    location: '上海',
    postedTime: '1天前',
    logo: 'https://logo800.cn/uploads/logoxinshang/58/logo800_16491625929115709.png',
    background: 'https://ts1.tc.mm.bing.net/th/id/OIP-C.rfb3sbui7JkXFrWow1jkjgHaEz?rs=1&pid=ImgDetMain&o=7&rm=3' // 添加背景图片
  }
])

const viewAll = () => {
  console.log('View all jobs')
}

const viewJobDetail = (job) => {
  console.log('View job detail:', job)
=======
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { jobAPI, collectJob, uncollectJob, checkJobCollected } from '@/api/enterprise'

const jobs = ref([])
const collectStatusMap = ref(new Map())

// 将后端岗位数据映射到 JobCard 需要的字段
const mapJob = (j) => ({
  id: j.jobId,
  title: j.jobName,
  company: j.enterprise?.enterpriseName || '',
  salary: j.salary || '',
  tags: j.tags || [],
  location: j.location || '',
  posted_time: j.createTime ? new Date(j.createTime).toLocaleDateString('zh-CN') : '',
  logo: j.enterprise?.imageUrl ? `http://localhost:7001${j.enterprise.imageUrl}` : '',
  background: '',
  isFavorite: false // 初始值，后续会更新
})

const fetchTopJobs = async () => {
  try {
    const params = {
      status: 'active',
      page: 1,
      pageSize: 8
      // 若后端支持排序参数，可加：sortBy: 'applicationCount', order: 'desc'
    }
    const res = await jobAPI.getJobList(params)
    const list = res?.data?.list || []
    // 前端按 applicationCount 降序排序
    list.sort((a, b) => (b.applicationCount || 0) - (a.applicationCount || 0))
    jobs.value = list.map(mapJob)
    
    // 获取收藏状态
    await fetchCollectStatus()
  } catch (e) {
    console.error('获取热门岗位失败:', e)
    ElMessage.error('获取热门岗位失败')
    jobs.value = []
  }
}

// 获取收藏状态
const fetchCollectStatus = async () => {
  if (jobs.value.length === 0) return
  
  try {
    const statusChecks = jobs.value.map(job => 
      checkJobCollected(job.id).catch(() => ({ data: { isCollected: false } }))
    )
    const results = await Promise.all(statusChecks)
    
    const newMap = new Map()
    jobs.value.forEach((job, index) => {
      const isCollected = results[index]?.data?.isCollected || false
      newMap.set(job.id, isCollected)
      job.isFavorite = isCollected
    })
    collectStatusMap.value = newMap
  } catch (error) {
    console.error('获取收藏状态失败:', error)
  }
}

// 处理收藏切换
const handleToggleFavorite = async (job) => {
  const jobId = job.id
  const isCollected = collectStatusMap.value.get(jobId)
  
  try {
    if (isCollected) {
      await uncollectJob(jobId)
      // 创建新的 Map 以触发响应式更新
      const newMap = new Map(collectStatusMap.value)
      newMap.set(jobId, false)
      collectStatusMap.value = newMap
      job.isFavorite = false
      ElMessage.success('取消收藏成功')
    } else {
      await collectJob(jobId)
      // 创建新的 Map 以触发响应式更新
      const newMap = new Map(collectStatusMap.value)
      newMap.set(jobId, true)
      collectStatusMap.value = newMap
      job.isFavorite = true
      ElMessage.success('收藏成功')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(isCollected ? '取消收藏失败' : '收藏失败')
  }
}

onMounted(fetchTopJobs)

const router = useRouter()
const viewAll = () => {
  router.push('/jobs')
}

const viewJobDetail = (job) => {
  router.push('/jobs')
>>>>>>> resume
}
</script>

<style lang="scss" scoped>
.recommended-jobs {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #303133;
    }
    
    .el-button {
      color: #6a5acd;
    }
  }
  
  .jobs-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 20px;
  }
<<<<<<< HEAD
=======

  .clickable {
    cursor: pointer;
  }
>>>>>>> resume
}
</style>